<template>
  <div class="content-container">
    <el-card>
      <!-- 查询部分 -->
      <el-form :model="query" :inline="true" class="demo-form-inline">
        <el-form-item label="租户名称">
          <el-input v-model="query.name" clearable />
        </el-form-item>
        <el-form-item label="租户账号">
          <el-input v-model="query.account" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="formQuery(false)">查询</el-button>
          <el-button type="warning" @click="formQuery(true)">重置</el-button>
          <el-button type="primary" @click="openDialog(null)">新增</el-button>
          <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="确认删除选中数据?" @confirm="removeRows"
            width="200px">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!-- 数据部分 -->
      <el-table max-height="600px" :data="tableData" stripe style="width: 100%; margin-top: 10px" ref="tableDataRef">
        <el-table-column type="selection" />
        <el-table-column prop="name" label="租户名称" />
        <el-table-column prop="account" label="租户账号" />
        <el-table-column prop="roleName" label="角色" />
        <el-table-column prop="charger" label="负责人" />
        <el-table-column prop="phone" label="联系方式" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="确认进行状态转换?"
              @confirm="changeStatus(scope.row.id)" width="200px">
              <template #reference>
                <el-button link :type="scope.row.status == 1 ? 'success' : 'danger'">
                  {{ scope.row.status == 1 ? '正常' : '禁用' }}
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="修改时间" width="180" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button @click="openDialog(scope.row)" link type="primary">
              编辑
            </el-button>
            <el-button @click="viewDialog(scope.row)" link type="success">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="margin-top: 20px">
        <el-pagination v-model:current-page="query.current" v-model:page-size="query.size"
          :page-sizes="[100, 200, 300, 400]" small background layout="total, sizes, prev, pager, next, jumper"
          :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <el-dialog v-model="dialogVisible" :title="(formData.id ? '编辑' : '新增') + '租户信息'" width="50%" :show-close="false"
        :close-on-click-modal="false">
        <el-form :rules="rules" :model="formData" class="demo-form-inline" ref="formDataRef">
          <el-form-item prop="name" label="租户名称">
            <el-input v-model="formData.name" clearable />
          </el-form-item>
          <el-form-item prop="account" label="租户账号">
            <el-input v-model="formData.account" clearable />
          </el-form-item>
          <el-form-item prop="roleId" label="租户角色">
            <el-select v-model="formData.roleId" clearable filterable>
              <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item prop="charger" label="负责人员">
            <el-input v-model="formData.charger" clearable />
          </el-form-item>
          <el-form-item prop="phone" label="联系方式">
            <el-input v-model="formData.phone" clearable />
          </el-form-item>
          <el-form-item prop="status" label="租户状态">
            <el-select v-model="formData.status" clearable filterable>
              <el-option v-for="item in [
                { label: '正常', value: 1 },
                { label: '禁用', value: 0 },
              ]" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="addr" label="租户地址">
            <el-input v-model="formData.addr" clearable />
          </el-form-item>
          <el-form-item prop="link" label="链接地址">
            <el-input v-model="formData.link" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="formSubmit">确认</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="viewVisible" width="50%" :show-close="false" :close-on-click-modal="false">
        <el-input v-model="viewData.name" disabled>
          <template #prepend>租户名称</template>
        </el-input>
        <el-input v-model="viewData.account" disabled>
          <template #prepend>租户账号</template>
        </el-input>
        <el-input v-model="viewData.roleName" disabled>
          <template #prepend>租户角色</template>
        </el-input>
        <el-input v-model="viewData.charger" disabled>
          <template #prepend>负责人员</template>
        </el-input>
        <el-input v-model="viewData.phone" disabled>
          <template #prepend>联系方式</template>
        </el-input>
        <el-input v-model="viewData.statusName" disabled>
          <template #prepend>租户状态</template>
        </el-input>
        <el-input v-model="viewData.link" disabled>
          <template #prepend>链接地址</template>
        </el-input>
        <el-input v-model="viewData.addr" disabled>
          <template #prepend>联系地址</template>
        </el-input>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="viewVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>
<script setup lang="ts" name="Tenant">
import { onMounted, ref, reactive, toRefs } from 'vue'
import type {
  Tenant,
  TenantModDTO,
  TenantQueryDTO,
  TenantVo,
} from '@/api/system/tenant/type'
import {
  switchStatus,
  tenantAdd,
  tenantDel,
  tenantMod,
  tenantQuery,
} from '@/api/system/tenant'
import { ElNotification } from 'element-plus'
import type { Role } from '@/api/acl/role/type.ts'
import { tenantRoles } from '@/api/acl/role'

const formDataRef = ref()
const tableDataRef = ref()
const initQuery = () => {
  return { current: 1, size: 10 } as TenantQueryDTO
}
const state = reactive<any>({
  query: initQuery(),
  tableData: [] as Tenant[],
  total: 0,
  dialogVisible: false,
  formData: {} as TenantModDTO,
  roleList: [] as Role[],
  viewVisible: false,
  viewData: {} as TenantVo,
  rules: {
    name: [{ required: true, message: '租户名称不能为空', trigger: 'blur' }],
    account: [{ required: true, message: '租户账号不能为空', trigger: 'blur' }],
    roleId: [{ required: true, message: '角色id不能为空', trigger: 'blur' }],
    charger: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
    phone: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
    status: [
      { required: true, message: '1-启用,0-禁用不能为空', trigger: 'blur' },
    ],
  },
})
const {
  query,
  tableData,
  total,
  dialogVisible,
  formData,
  rules,
  roleList,
  viewVisible,
  viewData,
} = toRefs(state)

const openDialog = (data: any) => {
  if (formDataRef.value) {
    formDataRef.value.resetFields()
  }

  formData.value = data == null ? {} : data
  dialogVisible.value = true
}
const viewDialog = (data: any) => {
  viewData.value = data
  viewVisible.value = true

  console.log(viewData.value)
}
const handleSizeChange = (size: number) => {
  query.value.size = size
  buildTable()
}
const handleCurrentChange = (current: number) => {
  query.value.current = current
  buildTable()
}
onMounted(() => {
  buildTable()
  buildRoles()
})
const buildRoles = async () => {
  const result = await tenantRoles()
  roleList.value = result.data
}
const buildTable = async () => {
  const result = await tenantQuery(query.value)
  tableData.value = result.data.rows
  total.value = result.data.total
}

const formQuery = (reset: boolean) => {
  reset ? (query.value = initQuery()) : query.value
  buildTable()
}
const formSubmit = async () => {
  await formDataRef.value?.validate()
  if (formData.value.id) {
    await tenantMod(formData.value)
  } else {
    await tenantAdd(formData.value)
  }
  dialogVisible.value = false
  await buildTable()
}
const removeRows = async () => {
  const rows = tableDataRef.value.getSelectionRows()
  if (rows.length == 0) {
    ElNotification({
      title: '删除失败',
      message: '请选择要删除的数据',
      type: 'warning',
    })
    return
  }
  const ids = rows.map((each: any) => each.id)
  await tenantDel({ ids: ids })
  await buildTable()
}
const changeStatus = async (id: string) => {
  await switchStatus(id)
  await buildTable()
}
</script>

<style scoped lang="scss">
.content-container {
  padding: 12px;
}
</style>